﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.DirectoryServices;
using Microsoft.Web.Administration;
using System.Threading;

namespace HostAssistantCore
{
	/// <summary>
	/// IIS7工具类(IIS8适用)
	/// </summary>
	public class UtilForIIS7 : UtilBase, IUtil
	{
        //private ServerManager server = new ServerManager();//创建iis管理对象
        private AddSiteUtil addsiteUtil = new AddSiteUtil();//添加站点工具

        public int CreateSite(SiteInfo siteinfo)
		{    
			int errorCode = ErrorCode.Succeed;
            if (siteinfo.SiteName != siteinfo.Username)//创建子站点
            {
                errorCode = CreateChildSite(siteinfo);
                return errorCode;
            }  
            /*
             * 获取站点根目录
             */
            string rootpath = siteinfo.PhysicalPath;
            if (rootpath.EndsWith("wwwroot"))
            {
                string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                if (!Extensions.EqualsRootPath(temp))
                {
                    rootpath = temp;
                }
            }
			try
			{   
                ServerManager server = new ServerManager();//IIS管理对象
                /*
                 * 判断站点是否存在
                 */
                errorCode = addsiteUtil.SiteExist(siteinfo.SiteName);
                if (errorCode == ErrorCode.SiteExists)
                {
                    errorCode = ErrorCode.SiteExists;
                    return errorCode;
                }
                else if (errorCode == ErrorCode.FindSiteError)
                {
                    errorCode = ErrorCode.iisStateError;
                    return errorCode;
                }
                else
                {
                    errorCode = ErrorCode.Succeed;
                }
                /*
                 * 判断用户是否存在
                 */
                if (addsiteUtil.UserExist(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"),siteinfo.Username) == ErrorCode.UserExist)
                {
                    errorCode = ErrorCode.UserExist;
                    return errorCode;
                }
                /*
                 * 判断路径是否存在
                 */

               
                    if (addsiteUtil.PathExist(siteinfo.PhysicalPath) == ErrorCode.PathExist)
                    {
                      //  errorCode = ErrorCode.PathExist;
                     //   return errorCode;
                    }
                    else
                {

              
              
              
                /*
                 * 创建目录
                 */
                try
                {  
                    System.IO.Directory.CreateDirectory(siteinfo.PhysicalPath);        
                }
                catch  (Exception ex)
                {
                    NLogger.Error(ex.ToString());
                    errorCode = ErrorCode.IOEXCEPTION;
                    return errorCode;
                }
                }
                /*
                 * 创建用户
                 */
                if (addsiteUtil.AddUser(siteinfo.Username, siteinfo.Password, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                if (addsiteUtil.AddUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolcomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp")) == ErrorCode.UserNotAdd)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    /*
                     * 回滚用户删除
                     */
                    addsiteUtil.delUser(siteinfo.SiteName);
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                /*
                 * 设置站点文件夹权限
                 */
                addsiteUtil.icaclsSet(siteinfo.SiteName, rootpath);
                addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, rootpath);
                /*
                 * 为空间设置配额
                 */
                //Quota.Add(siteinfo.PhysicalPath, siteinfo.SiteSize, "虚拟主机" + siteinfo.SiteName);//Mb为单位

                /*
                 * 创建应用池
                 */
                if (AppPoolUtil.CreatePoolWithID(siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpooltype"), siteinfo.NetVersion) == ErrorCode.poolNotBuild)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    /*
                     * 回滚用户删除
                     */
                    addsiteUtil.delUser(siteinfo.SiteName);
                    addsiteUtil.delUser("app_"+siteinfo.SiteName);
                    errorCode = ErrorCode.poolNotBuild;
                    return errorCode;
                }
                /*
                 * 创建站点
                 */
                try
                {
                    //启用父目录
                    addsiteUtil.SetAspParent();
                    
                    //初始化站点
                    string initdomain = siteinfo.Bindings[0].Split(":".ToArray())[0];
                    if (initdomain == "localhost")
                        initdomain = "";
                    Site site = server.Sites.Add(siteinfo.SiteName, "http", string.Format("*:{0}:{1}", siteinfo.Bindings[0].Split(":".ToArray())[1], initdomain), siteinfo.PhysicalPath);
                     /*
                     * 绑定域名
                     */
                    siteinfo.Bindings.RemoveAt(0);//移除第一个域名
                    foreach (string binding in siteinfo.Bindings)
                    {
                        string domain = binding.Split(":".ToArray())[0];
                        if (domain == "localhost")
                            domain = "";
                        string port = "80";
                        try
                        {
                            port = binding.Split(":".ToArray())[1];
                        }
                        catch
                        {
                            port = "80";
                        }
                        site.Bindings.Add(string.Format("*:{0}:{1}", port, domain), "http");
                    }
                    /*
                     * 设置日志路径
                     */
                    SiteLogFile logfile = site.LogFile;
                    string logpath = System.Configuration.ConfigurationManager.AppSettings.Get("logpath") + "\\" + siteinfo.SiteName;
                    if(!Directory.Exists(logpath))
                    {
                        Directory.CreateDirectory(logpath);
                    }
                    logfile.Directory = logpath;
                    logfile.Enabled = true;
                    logfile.LogFormat = LogFormat.W3c;
                    logfile.LogExtFileFlags = LogExtFileFlags.Date | LogExtFileFlags.Time | LogExtFileFlags.ClientIP | LogExtFileFlags.UserName | LogExtFileFlags.Method | LogExtFileFlags.UriStem | LogExtFileFlags.UriQuery | LogExtFileFlags.HttpStatus | LogExtFileFlags.BytesSent | LogExtFileFlags.UserAgent | LogExtFileFlags.Referer | LogExtFileFlags.ProtocolVersion | LogExtFileFlags.BytesRecv | LogExtFileFlags.TimeTaken;
                    logfile.LocalTimeRollover = true;
                    /*
                     * 设置站点访问权限
                     */
                    Application app = site.Applications[0];
                    VirtualDirectory virdir = app.VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                    virdir.UserName = siteinfo.SiteName;
                    virdir.Password = siteinfo.Password;
                    /*
                     * 设置最大绑定数
                     */
                    if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                        site.Limits.MaxBandwidth = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                    /*
                     * 设置最大连接数
                     */
                    if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                        site.Limits.MaxConnections = Convert.ToInt64(siteinfo.MaxConnections);
                    //提交更改
                    server.CommitChanges();
                    /*
                    * 指定应用程序池
                    */
                    addsiteUtil.connectPool(siteinfo.SiteName, siteinfo.SiteName);
                }
                    catch (Exception ex)
                {
                    NLogger.Error(ex.ToString());
                   
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    /*
                     * 回滚用户删除
                     */
                    addsiteUtil.delUser(siteinfo.SiteName);
                    addsiteUtil.delUser("app_" + siteinfo.SiteName);
                    /*
                     * 撤销更改
                     */
                    server.Dispose();
                    errorCode = ErrorCode.CommitFail;
                    return errorCode;
                }
               
                /*
                 * 设置PHP引擎
                 */
                if (siteinfo.Phppath != "")
                {
                    /*
                    * 设置全局php引擎
                    */
                    addsiteUtil.SetGPhpEngine(siteinfo.Phppath);
                    /*
                    * php站点引擎
                    */
                    addsiteUtil.SetPhpEngine(siteinfo.SiteName, siteinfo.Phppath);
                }
                /*
                 * 设置站点限制
                 */
                addsiteUtil.SiteLimited(siteinfo.SiteName, siteinfo.Cpulimit, siteinfo.Memeroy);
                /*
                 * 设置默认文档
                 */
                if (siteinfo.DefaultDocuments.Count != 0)
                {
                    if (addsiteUtil.SetDefaultDocument(siteinfo.SiteName, siteinfo.DefaultDocuments, true) == ErrorCode.setDefaultDocFail)
                    {
                        errorCode = ErrorCode.setDefaultDocFail;
                    }
                }
                /*
                 * 创建FTP
                 */
                if (siteinfo.Password != System.Configuration.ConfigurationManager.AppSettings.Get("defaultpassword"))
                {
                    /*
                    * 创建FTP工具
                    */
                    FtpUtil ftputil = new FtpUtil();
                    /*
                    * 处理ftp目录
                    */
                 






                   errorCode = ftputil.createFtpPoint(siteinfo.SiteName, rootpath);


                   


                    //创建FTP
                    if (errorCode == ErrorCode.ftpExists)
                    {
                        errorCode = ErrorCode.ftpExists;
                    }
                    else if (errorCode == ErrorCode.ftpSiteFail)
                    {
                        errorCode = ErrorCode.ftpSiteFail;
                    }
                }
                /*
                 * 设置日志文件开启状态
                 */
                /*
                 * 复制Hello页面到站点目录
                 */
                string root = System.Environment.CurrentDirectory;
                string hellopath = root + "/conf/" + "hello.htm";
                string sitepath = System.IO.Path.Combine(@siteinfo.PhysicalPath, System.IO.Path.GetFileName(@hellopath));
                System.IO.File.Copy(@hellopath, sitepath,true);
                /*
                 * 启动站点
                 */
                errorCode = addsiteUtil.siteStart(siteinfo.SiteName);
                if (errorCode == ErrorCode.iisStateError)
                {
                    errorCode = ErrorCode.iisStateError;
                    siteinfo.Sstate = "off";
                }
                else if (errorCode == ErrorCode.siteStateError)
                {
                    errorCode = ErrorCode.siteStateError;
                    siteinfo.Sstate = "off";
                }
                else
                {
                    errorCode = ErrorCode.Succeed;
                    siteinfo.Sstate = "on";
                }
                /*
                 * 将新建的站点数据存储到数据库表
                 */
                if (IISAdoHelper.adoSaveNewSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
                {
                    errorCode = ErrorCode.saveNewSiteFail;
                }
                else
                {
                    if (siteinfo.Password != System.Configuration.ConfigurationManager.AppSettings.Get("defaultpassword"))
                    {
                        string insert_sql = "insert into Ftpsite(Name,Pwd,OperPower,Path,CreTime,iisversion) values(@Name,@Pwd,@OperPower,@Path,@CreTime,@iisversion)";       //插入的SQL语句(带参数)
                        Ftpsite Ftpsite = new Ftpsite();

                        Ftpsite.Name = siteinfo.SiteName;

                        Ftpsite.Pwd = siteinfo.Password;

                        Ftpsite.Path = siteinfo.PhysicalPath;

                        Ftpsite.CreTime = DateTime.Now.ToString();

                        Ftpsite.OperPower = "读写";
                        Data<Ftpsite>.GetInstance().Add(insert_sql, Ftpsite);

                        NLogger.Error("创建FTP3");

                        string update_sql = "update Sites set  ftpname=@ftpname where  sname=@sname ";
                        Sites Sites = new Sites();
                        Sites.ftpname = siteinfo.SiteName;
                        Sites.sname = siteinfo.SiteName;
                        Data<Sites>.GetInstance().Update(update_sql, Sites);

                        NLogger.Error("创建FTP4");
                    }

                }




            }
			catch (Exception ex)
			{
                NLogger.Error(ex.ToString());
				errorCode = ErrorCode.Unknown;
			}

			return errorCode;
		}

        public int R_CreateSite(SiteInfo siteinfo)
        {
            // pool flag
            bool pool_flag = true;
            int errorCode = ErrorCode.Succeed;
            if (siteinfo.SiteName != siteinfo.Username)//创建子站点
            {
                errorCode = CreateChildSite(siteinfo);
                return errorCode;
            }
            /*
             * 获取站点根目录
             */
            string rootpath = siteinfo.PhysicalPath;
            if (rootpath.EndsWith("wwwroot"))
            {
                string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                if (!Extensions.EqualsRootPath(temp))
                {
                    rootpath = temp;
                }
            }
            try
            {
                ServerManager server = new ServerManager();//IIS管理对象
                /*
                 * 判断站点是否存在
                 */
                errorCode = addsiteUtil.SiteExist(siteinfo.SiteName);
                if (errorCode == ErrorCode.SiteExists)
                {
                    errorCode = ErrorCode.SiteExists;
                    return errorCode;
                }
                else if (errorCode == ErrorCode.FindSiteError)
                {
                    errorCode = ErrorCode.iisStateError;
                    return errorCode;
                }
                else
                {
                    errorCode = ErrorCode.Succeed;
                }
                /*
                 * 判断用户是否存在
                 */
                if (addsiteUtil.UserExist(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"), siteinfo.Username) == ErrorCode.UserExist)
                {
                    errorCode = ErrorCode.UserExist;
                    return errorCode;
                }
                /*
                 * 判断路径是否存在
                 */
                //if (addsiteUtil.PathExist(siteinfo.PhysicalPath) == ErrorCode.PathExist)
                //{
                //    errorCode = ErrorCode.PathExist;
                //    return errorCode;
                //}
                /*
                 * 创建目录
                 */
                try
                {
                    System.IO.Directory.CreateDirectory(siteinfo.PhysicalPath);
                }
                catch
                {
                    errorCode = ErrorCode.IOEXCEPTION;
                    return errorCode;
                }
                /*
                 * 创建用户
                 */
                if (addsiteUtil.AddUser(siteinfo.Username, siteinfo.Password, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                if (siteinfo.SiteName.Length > 16)
                {
                    pool_flag = false;
                }
                else
                {
                    if (addsiteUtil.AddUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolcomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp")) == ErrorCode.UserNotAdd)
                    {
                        /*
                         * 回滚目录的创建
                         */
                        if (Directory.Exists(siteinfo.PhysicalPath))
                        {
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                            if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                            {
                                //如果目录为空删除
                                System.IO.Directory.Delete(siteinfo.PhysicalPath);
                            }

                        }
                        /*
                         * 回滚用户删除
                         */
                        addsiteUtil.delUser(siteinfo.SiteName);
                        errorCode = ErrorCode.UserNotAdd;
                        return errorCode;
                    }
                }
                /*
                 * 设置站点文件夹权限
                 */
                addsiteUtil.icaclsSet(siteinfo.SiteName, rootpath);
                addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, rootpath);
                /*
                 * 为空间设置配额
                 */
                //Quota.Add(siteinfo.PhysicalPath, siteinfo.SiteSize, "虚拟主机" + siteinfo.SiteName);//Mb为单位

                /*
                 * 创建应用池
                 */
                if (pool_flag)
                {
                    if (AppPoolUtil.CreatePoolWithID(siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpooltype"), siteinfo.NetVersion) == ErrorCode.poolNotBuild)
                    {
                        /*
                         * 回滚目录的创建
                         */
                        if (Directory.Exists(siteinfo.PhysicalPath))
                        {
                            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                            if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                            {
                                //如果目录为空删除
                                System.IO.Directory.Delete(siteinfo.PhysicalPath);
                            }
                        }
                        /*
                         * 回滚用户删除
                         */
                        addsiteUtil.delUser(siteinfo.SiteName);
                        addsiteUtil.delUser("app_" + siteinfo.SiteName);
                        errorCode = ErrorCode.poolNotBuild;
                        return errorCode;
                    }
                }
                /*
                 * 创建站点
                 */
                try
                {
                    //启用父目录
                    addsiteUtil.SetAspParent();

                    //初始化站点
                    string initdomain = siteinfo.Bindings[0].Split(":".ToArray())[0];
                    if (initdomain == "localhost")
                        initdomain = "";
                    Site site = server.Sites.Add(siteinfo.SiteName, "http", string.Format("*:{0}:{1}", siteinfo.Bindings[0].Split(":".ToArray())[1], initdomain), siteinfo.PhysicalPath);
                    /*
                    * 绑定域名
                    */
                    siteinfo.Bindings.RemoveAt(0);//移除第一个域名
                    foreach (string binding in siteinfo.Bindings)
                    {
                        string domain = binding.Split(":".ToArray())[0];
                        if (domain == "localhost")
                            domain = "";
                        string port = "80";
                        try
                        {
                            port = binding.Split(":".ToArray())[1];
                        }
                        catch
                        {
                            port = "80";
                        }
                        site.Bindings.Add(string.Format("*:{0}:{1}", port, domain), "http");
                    }
                    /*
                     * 设置日志路径
                     */
                    SiteLogFile logfile = site.LogFile;
                    string logpath = System.Configuration.ConfigurationManager.AppSettings.Get("logpath") + "\\" + siteinfo.SiteName;
                    if (!Directory.Exists(logpath))
                    {
                        Directory.CreateDirectory(logpath);
                    }
                    logfile.Directory = logpath;
                    logfile.Enabled = true;
                    logfile.LogFormat = LogFormat.W3c;
                    logfile.LogExtFileFlags = LogExtFileFlags.Date | LogExtFileFlags.Time | LogExtFileFlags.ClientIP | LogExtFileFlags.UserName | LogExtFileFlags.Method | LogExtFileFlags.UriStem | LogExtFileFlags.UriQuery | LogExtFileFlags.HttpStatus | LogExtFileFlags.BytesSent | LogExtFileFlags.UserAgent | LogExtFileFlags.Referer | LogExtFileFlags.ProtocolVersion | LogExtFileFlags.BytesRecv | LogExtFileFlags.TimeTaken;
                    logfile.LocalTimeRollover = true;
                    /*
                     * 设置站点访问权限
                     */
                    Application app = site.Applications[0];
                    VirtualDirectory virdir = app.VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                    virdir.UserName = siteinfo.SiteName;
                    virdir.Password = siteinfo.Password;
                    /*
                     * 设置最大绑定数
                     */
                    if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                        site.Limits.MaxBandwidth = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                    /*
                     * 设置最大连接数
                     */
                    if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                        site.Limits.MaxConnections = Convert.ToInt64(siteinfo.MaxConnections);
                    //提交更改
                    server.CommitChanges();
                    /*
                    * 指定应用程序池
                    */
                    if (pool_flag)
                    {
                        addsiteUtil.connectPool(siteinfo.SiteName, siteinfo.SiteName);
                    }
                }
                catch
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    /*
                     * 回滚用户删除
                     */
                    addsiteUtil.delUser(siteinfo.SiteName);
                    addsiteUtil.delUser("app_" + siteinfo.SiteName);
                    /*
                     * 撤销更改
                     */
                    server.Dispose();
                    errorCode = ErrorCode.CommitFail;
                    return errorCode;
                }

                /*
                 * 设置PHP引擎
                 */
                if (siteinfo.Phppath != "")
                {
                    /*
                    * 设置全局php引擎
                    */
                    addsiteUtil.SetGPhpEngine(siteinfo.Phppath);
                    /*
                    * php站点引擎
                    */
                    addsiteUtil.SetPhpEngine(siteinfo.SiteName, siteinfo.Phppath);
                }
                /*
                 * 设置站点限制
                 */
                addsiteUtil.SiteLimited(siteinfo.SiteName, siteinfo.Cpulimit, siteinfo.Memeroy);
                /*
                 * 将新建的站点数据存储到数据库表
                 */
                if (IISAdoHelper.adoSaveNewSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
                {
                    errorCode = ErrorCode.saveNewSiteFail;
                }

                /*
                 * 设置默认文档
                 */
                if (siteinfo.DefaultDocuments.Count != 0)
                {
                    if (addsiteUtil.SetDefaultDocument(siteinfo.SiteName, siteinfo.DefaultDocuments, true) == ErrorCode.setDefaultDocFail)
                    {
                        errorCode = ErrorCode.setDefaultDocFail;
                    }
                }
                /*
                 * 创建FTP
                 */
                if (siteinfo.Password != System.Configuration.ConfigurationManager.AppSettings.Get("defaultpassword") && siteinfo.Password != "")
                {

                    NLogger.Error("创建FTP1");
                    /*
                    * 创建FTP工具
                    */
                    FtpUtil ftputil = new FtpUtil();
                    /*
                    * 处理ftp目录
                    */
                    errorCode = ftputil.createFtpPoint(siteinfo.SiteName, rootpath);

                    NLogger.Error("创建FTP2"+ errorCode.ToString());

                    ////string insert_sql = "insert into Ftpsite(Name,Pwd,OperPower,Path,CreTime,iisversion) values(@Name,@Pwd,@OperPower,@Path,@CreTime,@iisversion)";       //插入的SQL语句(带参数)
                    ////Ftpsite Ftpsite = new Ftpsite();

                    ////Ftpsite.Name = siteinfo.SiteName;

                    ////Ftpsite.Pwd = siteinfo.Password;

                    ////Ftpsite.Path = siteinfo.PhysicalPath;

                    ////Ftpsite.CreTime = DateTime.Now.ToString();

                    ////Ftpsite.OperPower = "读写";
                    ////Data<Ftpsite>.GetInstance().Add(insert_sql, Ftpsite);

                    ////NLogger.Error("创建FTP3");

                    ////string update_sql = "update Sites set  ftpname=@ftpname where  sname=@sname ";
                    ////Sites Sites = new Sites();
                    ////Sites.ftpname = siteinfo.SiteName;
                    ////Sites.sname = siteinfo.SiteName;
                    ////Data<Sites>.GetInstance().Update(update_sql, Sites);

                    ////NLogger.Error("创建FTP4");
                    //创建FTP
                    if (errorCode == ErrorCode.ftpExists)
                    {
                        errorCode = ErrorCode.ftpExists;
                    }
                    else if (errorCode == ErrorCode.ftpSiteFail)
                    {
                        errorCode = ErrorCode.ftpSiteFail;
                    }
                }
                /*
                 * 设置日志文件开启状态
                 */
                /*
                 * 复制Hello页面到站点目录
                 */
                string root = System.Environment.CurrentDirectory;
                string hellopath = root + "/conf/" + "hello.htm";
                string sitepath = System.IO.Path.Combine(@siteinfo.PhysicalPath, System.IO.Path.GetFileName(@hellopath));
                System.IO.File.Copy(@hellopath, sitepath, true);
                /*
                 * 启动站点
                 */
                errorCode = addsiteUtil.siteStart(siteinfo.SiteName);
                if (errorCode == ErrorCode.iisStateError)
                {
                    errorCode = ErrorCode.iisStateError;
                    siteinfo.Sstate = "off";
                }
                else if (errorCode == ErrorCode.siteStateError)
                {
                    errorCode = ErrorCode.siteStateError;
                    siteinfo.Sstate = "off";
                }
                else
                {
                    errorCode = ErrorCode.Succeed;
                    siteinfo.Sstate = "on";
                }
                //提交更改
                server.CommitChanges();
            }
            catch
            {
                errorCode = ErrorCode.Unknown;
            }

            return errorCode;
        }

        #region 创建子站点
        /// <summary>
        /// 创建子站点
        /// </summary>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public int CreateChildSite(SiteInfo siteinfo)
        {
            string sitename = siteinfo.Username;
            string password = siteinfo.Password;
            int errorCode = ErrorCode.Succeed;
            try
            {
                ServerManager server = new ServerManager();//IIS管理对象
                /*
                 * 判断站点是否存在
                 */
                errorCode = addsiteUtil.SiteExist(siteinfo.SiteName);
                if (errorCode == ErrorCode.SiteExists)
                {
                    errorCode = ErrorCode.SiteExists;
                    return errorCode;
                }
                else if (errorCode == ErrorCode.FindSiteError)
                {
                    errorCode = ErrorCode.iisStateError;
                    return errorCode;
                }
                else
                {
                    errorCode = ErrorCode.Succeed;
                }
                /*
                 * 判断路径是否存在
                 */
                //if (addsiteUtil.PathExist(siteinfo.PhysicalPath) == ErrorCode.PathExist)
                //{
                //    errorCode = ErrorCode.PathExist;
                //    return errorCode;
                //}
                /*
                 * 创建目录
                 */
                try
                {
                    System.IO.Directory.CreateDirectory(siteinfo.PhysicalPath);
                }
                catch
                {
                    errorCode = ErrorCode.IOEXCEPTION;
                    return errorCode;
                }
                /*
                 * 创建站点
                 */
                try
                {
                    //启用父目录
                    addsiteUtil.SetAspParent();

                    //初始化站点
                    string initdomain = siteinfo.Bindings[0].Split(":".ToArray())[0];
                    if (initdomain == "localhost")
                        initdomain = "";
                    Site site = server.Sites.Add(siteinfo.SiteName, "http", string.Format("*:{0}:{1}", siteinfo.Bindings[0].Split(":".ToArray())[1], initdomain), siteinfo.PhysicalPath);
                    /*
                    * 绑定域名
                    */
                    siteinfo.Bindings.RemoveAt(0);//移除第一个域名
                    foreach (string binding in siteinfo.Bindings)
                    {
                        string domain = binding.Split(":".ToArray())[0];
                        if (domain == "localhost")
                            domain = "";
                        string port = "80";
                        try
                        {
                            port = binding.Split(":".ToArray())[1];
                        }
                        catch
                        {
                            port = "80";
                        }
                        site.Bindings.Add(string.Format("*:{0}:{1}", port, domain), "http");
                    }
                    /*
                     * 设置日志路径
                     */
                    SiteLogFile logfile = site.LogFile;
                    string logpath = System.Configuration.ConfigurationManager.AppSettings.Get("logpath") + "\\" + siteinfo.SiteName;
                    if (!Directory.Exists(logpath))
                    {
                        Directory.CreateDirectory(logpath);
                    }
                    logfile.Directory = logpath;
                    logfile.Enabled = true;
                    logfile.LogFormat = LogFormat.W3c;
                    logfile.LogExtFileFlags = LogExtFileFlags.Date | LogExtFileFlags.Time | LogExtFileFlags.ClientIP | LogExtFileFlags.UserName | LogExtFileFlags.Method | LogExtFileFlags.UriStem | LogExtFileFlags.UriQuery | LogExtFileFlags.HttpStatus | LogExtFileFlags.BytesSent | LogExtFileFlags.UserAgent | LogExtFileFlags.Referer | LogExtFileFlags.ProtocolVersion | LogExtFileFlags.BytesRecv | LogExtFileFlags.TimeTaken;
                    logfile.LocalTimeRollover = true;
                    /*
                     * 设置站点访问权限
                     */
                    Application app = site.Applications[0];
                    VirtualDirectory virdir = app.VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                    virdir.UserName = sitename;
                    virdir.Password = password;
                    /*
                     * 设置最大绑定数
                     */
                    if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                        site.Limits.MaxBandwidth = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                    /*
                     * 设置最大连接数
                     */
                    if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                        site.Limits.MaxConnections = Convert.ToInt64(siteinfo.MaxConnections);
                    //提交更改
                    server.CommitChanges();
                    /*
                    * 指定应用程序池
                    */
                    addsiteUtil.connectPool(siteinfo.SiteName, sitename);
                }
                catch
                {
                    /*
                     * 回滚目录的创建
                     */
                    if (Directory.Exists(siteinfo.PhysicalPath))
                    {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@siteinfo.PhysicalPath);
                        if (di.GetFiles().Length + di.GetDirectories().Length == 0)
                        {
                            //如果目录为空删除
                            System.IO.Directory.Delete(siteinfo.PhysicalPath);
                        }
                    }
                    /*
                     * 撤销更改
                     */
                    server.Dispose();
                    errorCode = ErrorCode.CommitFail;
                    return errorCode;
                }

                /*
                 * 设置PHP引擎
                 */
                if (siteinfo.Phppath != "")
                {
                    /*
                    * 设置全局php引擎
                    */
                    addsiteUtil.SetGPhpEngine(siteinfo.Phppath);
                    /*
                    * php站点引擎
                    */
                    addsiteUtil.SetPhpEngine(siteinfo.SiteName, siteinfo.Phppath);
                }
                /*
                 * 设置站点限制
                 */
                addsiteUtil.SiteLimited(siteinfo.SiteName, siteinfo.Cpulimit, siteinfo.Memeroy);
                /*
                 * 将新建的站点数据存储到数据库表
                 */
                if (IISAdoHelper.adoSaveNewSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
                {
                    errorCode = ErrorCode.saveNewSiteFail;
                }

                /*
                 * 设置默认文档
                 */
                if (siteinfo.DefaultDocuments.Count != 0)
                {
                    if (addsiteUtil.SetDefaultDocument(siteinfo.SiteName, siteinfo.DefaultDocuments, true) == ErrorCode.setDefaultDocFail)
                    {
                        errorCode = ErrorCode.setDefaultDocFail;
                    }
                }
                /*
                 * 复制Hello页面到站点目录
                 */
                string root = System.Environment.CurrentDirectory;
                string hellopath = root + "/conf/" + "hello.htm";
                string sitepath = System.IO.Path.Combine(@siteinfo.PhysicalPath, System.IO.Path.GetFileName(@hellopath));
                System.IO.File.Copy(@hellopath, sitepath, true);
                /*
                 * 启动站点
                 */
                errorCode = addsiteUtil.siteStart(siteinfo.SiteName);
                if (errorCode == ErrorCode.iisStateError)
                {
                    errorCode = ErrorCode.iisStateError;
                    siteinfo.Sstate = "off";
                }
                else if (errorCode == ErrorCode.siteStateError)
                {
                    errorCode = ErrorCode.siteStateError;
                    siteinfo.Sstate = "off";
                }
                else
                {
                    errorCode = ErrorCode.Succeed;
                    siteinfo.Sstate = "on";
                }
                //提交更改
                server.CommitChanges();
            }
            catch
            {
                errorCode = ErrorCode.Unknown;
            }

            return errorCode;
        }
        #endregion

        /// <summary>
        /// 编辑站点
        /// </summary>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public int SetSite(SiteInfo siteinfo)
        {
            int errorCode = ErrorCode.SetSucceed;
            //ServerManager server = new ServerManager();
            //Configuration config = server.GetApplicationHostConfiguration();
            //Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
            try
            {
                /*
                * 设置站点路径日志路径
                */
                if (siteinfo.PhysicalPath != "")
                {
                    ServerManager server = new ServerManager();
                    Configuration config = server.GetApplicationHostConfiguration();
                    Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
                    string disk = siteinfo.PhysicalPath.Substring(0, 1);
                    string logpath = disk + System.Configuration.ConfigurationManager.AppSettings.Get("logpath").Substring(1, System.Configuration.ConfigurationManager.AppSettings.Get("logpath").Length - 1) + "\\" + siteinfo.SiteName;
                    if (!Directory.Exists(logpath))
                    {
                        Directory.CreateDirectory(logpath);
                    }
                    if (!Directory.Exists(siteinfo.PhysicalPath))
                    {
                        Directory.CreateDirectory(siteinfo.PhysicalPath);
                    }
                    var sitelog = site.LogFile;
                    sitelog.Directory = logpath;

                    ConfigurationSection sitesection = config.GetSection("system.applicationHost/sites");
                    ConfigurationElementCollection sites = sitesection.GetCollection();
                    foreach (ConfigurationElement sitechild in sites)
                    {
                        string sitename = sitechild.GetAttributeValue("name").ToString();
                        if (sitename == siteinfo.SiteName)
                        {
                            sitechild.GetCollection()[0].GetCollection()[0].SetAttributeValue("physicalPath", siteinfo.PhysicalPath);
                        }
                    }
                    // set priviliges
                    addsiteUtil.icaclsSet(siteinfo.SiteName, siteinfo.PhysicalPath);
                    addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.PhysicalPath);
                    server.CommitChanges();
                }
                /*
                 * 设置绑定信息
                 */
                if (siteinfo.Bindings != null)
                {
                    ServerManager server = new ServerManager();
                    Configuration config = server.GetApplicationHostConfiguration();
                    Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
                    /*
                     * 移除所有绑定
                     */
                    int bindscount = site.Bindings.Count();
                    for (int i = 0; i < bindscount; i++)
                    {
                        site.Bindings.RemoveAt(0);
                    }
                    //foreach (Binding binding in site.Bindings)
                    //{
                    //    site.Bindings.RemoveAt(0);
                    //    site.Bindings.RemoveAt(1);
                    //}
                    foreach (string binding in siteinfo.Bindings)
                    {
                        /*
                         * 添加绑定
                         */
                        string domain = binding.Split(":".ToArray())[0];
                        if (domain == "localhost")
                            domain = "";
                        string port = "80";
                        try
                        {
                            port = binding.Split(":".ToArray())[1];
                        }
                        catch
                        {
                            port = "80";
                        }
                        site.Bindings.Add(string.Format("*:{0}:{1}", port, domain), "http");
                    }
                    server.CommitChanges();
                }
                /*
                 * 更改ftp密码
                 * 判断是否存在ftp 不存在创建
                 * 只要更改用户密码
                 * 还要更改站点密码
                 */
                //if (siteinfo.Password != "")
                //{
                //    //判断用户是否存在 不存在 添加
                //    if (!ADUser.ExistUser(siteinfo.SiteName))
                //    {
                //        /*
                //        * 创建用户
                //        */
                //        addsiteUtil.AddUser(siteinfo.SiteName, siteinfo.Password, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"));
                //    }
                //    else
                //    {
                //        ADUser.PwdModify(siteinfo.SiteName, siteinfo.Password);
                //    }
                //    //判断用户是否存在 不存在 添加
                //    if (!ADUser.ExistUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName))
                //    {
                //        /*
                //        * 创建用户
                //        */
                //        addsiteUtil.AddUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolcomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp"));
                //        /*
                //         * 创建应用池
                //         */
                //        AppPoolUtil.CreatePoolWithID_Q(siteinfo.SiteName, siteinfo.Password + System.Configuration.ConfigurationManager.AppSettings.Get("cpoolpass"), System.Configuration.ConfigurationManager.AppSettings.Get("cpooltype"), siteinfo.NetVersion);
                //        /*
                //        * 指定应用程序池
                //        */
                //        addsiteUtil.connectPool(siteinfo.SiteName, siteinfo.SiteName);
                //    }
                //    try
                //    {
                //        /*
                //         * 创建FTP工具
                //         */
                //        FtpUtil ftputil = new FtpUtil();
                //        string sitename = siteinfo.SiteName;
                //        if (!ftputil.getFtpState(siteinfo.SiteName))
                //        {
                //            /*
                //             * 获取站点根目录
                //             */
                //            string rootpath = siteinfo.PhysicalPath;
                //            if (rootpath.EndsWith("wwwroot"))
                //            {
                //                string temp = rootpath.Substring(0, rootpath.LastIndexOf("wwwroot") - 1);
                //                if (!Extensions.EqualsRootPath(temp))
                //                {
                //                    rootpath = temp;
                //                }
                //            }
                //            /*
                //             * 创建FTP
                //             */
                //            if (System.Configuration.ConfigurationManager.AppSettings.Get("ftpornot") == "yes")//如果存在FTP服务器才创建
                //            {
                //                /*
                //                 * 设置站点文件夹权限
                //                 */
                //                if(!addsiteUtil.FileSP_Exists(rootpath,siteinfo.SiteName))
                //                {
                //                    addsiteUtil.icaclsSet(siteinfo.SiteName, rootpath);
                //                }
                //                if (!addsiteUtil.FileSP_Exists(rootpath, System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName))
                //                {
                //                    addsiteUtil.icaclsSet(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + siteinfo.SiteName, rootpath);
                //                }
                //                //创建FTP
                //                ftputil.createFtpPoint(siteinfo.SiteName, rootpath);
                //            }
                //        }
                //    }
                //    catch (Exception EX)
                //    {
                //        NLogger.Error(EX.ToString());
                //    }

                //    ServerManager server = new ServerManager();
                //    Configuration config = server.GetApplicationHostConfiguration();
                //    Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
                    
                //    /*
                //     * 设置站点访问权限
                //     */
                //    Application app = site.Applications[0];
                //    VirtualDirectory virdir = app.VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                //    virdir.Password = siteinfo.Password;
                //    server.CommitChanges();
                //}

                /*
                 * 修改.net版本
                 */
                if (siteinfo.NetVersion != "")
                {
                    ServerManager server = new ServerManager();
                    Configuration config = server.GetApplicationHostConfiguration();
                    Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
                    server.ApplicationPools[siteinfo.Username].ManagedRuntimeVersion = siteinfo.NetVersion;
                    server.CommitChanges();
                }
                /*
                 * 修改phppath
                 */
                if (siteinfo.Phppath != "")
                {
                    addsiteUtil.NSetPhpEngine(siteinfo.SiteName, siteinfo.Phppath);
                }
                else
                {
                    addsiteUtil.WSetPhpEngine(siteinfo.SiteName);
                }
                /*
                 * 修改主页
                 */
                if(siteinfo.DefaultDocuments != null)
                    addsiteUtil.SetDefaultDocument(siteinfo.SiteName, siteinfo.DefaultDocuments, true);
                /*
                 * 设置限制
                 */
                if (siteinfo.MaxBandwidth != "0" && siteinfo.MaxBandwidth != "-1")
                {
                    ServerManager server = new ServerManager();
                    Configuration config = server.GetApplicationHostConfiguration();
                    Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
                    site.Limits.MaxBandwidth = Convert.ToInt64(siteinfo.MaxBandwidth) * 1024 * 1024;
                    server.CommitChanges();
                }
                if (siteinfo.MaxConnections != "0" && siteinfo.MaxConnections != "-1")
                {
                    ServerManager server = new ServerManager();
                    Configuration config = server.GetApplicationHostConfiguration();
                    Site site = server.Sites.FirstOrDefault(o => o.Name == siteinfo.SiteName);//查找到指定站点
                    site.Limits.MaxConnections = Convert.ToInt64(siteinfo.MaxConnections);
                    server.CommitChanges();
                }
                addsiteUtil.SiteLimited(siteinfo.Username, siteinfo.Cpulimit, siteinfo.Memeroy);
                /*
                * 将新建的站点数据存储到数据库表
                */

                 
                if (IISAdoHelper.adoSaveNowSite(siteinfo.SiteName) == ErrorCode.saveNewSiteFail)
                {
                    errorCode = ErrorCode.saveNewSiteFail;
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                errorCode = ErrorCode.SetFail;
            }

            return errorCode;
        }

		public int RemoveSite(string siteName)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//找指定站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				//存在才移除
				if(targetSite != null)
				{
					server.Sites.Remove(targetSite);
					server.CommitChanges();
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int CreateAppPool(string poolName)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//先检查是否已存在
				bool exists = false;
				foreach(var pool in server.ApplicationPools)
				{
					if(pool.Name.EqualsEx(poolName))
					{
						exists = true;
						break;
					}
				}

				//不存在才创建
				if(!exists)
				{
					var appPool = server.ApplicationPools.Add(poolName);
					appPool.ManagedRuntimeVersion = "v4.0";							//指定dotnet4.0，集成模式
					appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
					appPool.QueueLength = 10000;
					server.CommitChanges();
				}
				else
				{
					errorCode = ErrorCode.AppPoolExists;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int RemoveAppPool(string poolName)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//找指定的应用程序池
				ApplicationPool targetPool = null;
				foreach(var pool in server.ApplicationPools)
				{
					if(pool.Name.EqualsEx(poolName))
					{
						targetPool = pool;
						break;
					}
				}

				//存在才移除
				if(targetPool != null)
				{
					server.ApplicationPools.Remove(targetPool);
					server.CommitChanges();
				}
				else
				{
					errorCode = ErrorCode.AppPoolNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int CreateDir(string siteName, string virtualPath, string physicalPath, bool enableAllMimeTypes)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//先找站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				if(targetSite != null)
				{
					//找根应用
					Application rootApp = null;
					foreach(var app in targetSite.Applications)
					{
						if(app.Path.Equals("/"))
						{
							rootApp = app;
							break;
						}
					}

					//存在根应用才能创建
					if(rootApp != null)
					{
						bool exists = false;
						foreach(var dir in rootApp.VirtualDirectories)
						{
							if(dir.Path.EqualsEx(virtualPath))
							{
								exists = true;
								break;
							}
						}

						if(!exists)
						{
							var dir = rootApp.VirtualDirectories.Add(virtualPath, physicalPath);

							//处理Mime Types
							if(enableAllMimeTypes)
							{
                                /*  路径映射存在问题，会向错误的位置写web.config，未解决，改用直接写文件的方法
								var config = server.GetWebConfiguration(targetSite.Name, dir.Path);
								var mimes = config.GetSection("system.webServer/staticContent").GetCollection();

								var mimeTypeSection = mimes.CreateElement("mimeMap");
								mimeTypeSection["fileExtension"] = ".*";
								mimeTypeSection["mimeType"] = "application/*";
								mimes.AddAt(0, mimeTypeSection);
								*/



                                ////                             <? xml version = "1.0" encoding = "UTF-8" ?>
                                ////< configuration >

                                ////    < system.webServer >

                                ////        < staticContent >

                                ////            < mimeMap fileExtension = ".*" mimeType = "application/octet-stream" />

                                ////           </ staticContent >

                                ////       </ system.webServer >
                                ////   </ configuration >





                                string receivePath = System.Windows.Forms.Application.StartupPath + "\\file\\webconfig.txt";

                                string strs2 = File.ReadAllText(receivePath, Encoding.UTF8);


                                string path = Path.Combine(physicalPath, "web.config");
                              File.WriteAllText(path, strs2, Encoding.UTF8);
							}

							server.CommitChanges();
						}
						else
						{
							errorCode = ErrorCode.VirtualDirExists;
						}
					}
					else
					{
						errorCode = ErrorCode.RootAppNotFound;
					}
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int RemoveDir(string siteName, string virtualPath)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//先找站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				if(targetSite != null)
				{
					//找根应用
					Application rootApp = null;
					foreach(var app in targetSite.Applications)
					{
						if(app.Path.Equals("/"))
						{
							rootApp = app;
							break;
						}
					}

					//存在根应用才能删除
					if(rootApp != null)
					{
						VirtualDirectory targetDir = null;
						foreach(var dir in rootApp.VirtualDirectories)
						{
							if(dir.Path.EqualsEx(virtualPath))
							{
								targetDir = dir;
								break;
							}
						}

						if(targetDir != null)
						{
							rootApp.VirtualDirectories.Remove(targetDir);
							server.CommitChanges();
						}
						else
						{
							errorCode = ErrorCode.VirtualDirNotFound;
						}
					}
					else
					{
						errorCode = ErrorCode.RootAppNotFound;
					}
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int CreateApp(string siteName, string virtualPath, string physicalPath, string poolName, bool useSsl)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//先找站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				if(targetSite != null)
				{
					//再找应用
					bool exists = false;
					foreach(var app in targetSite.Applications)
					{
						if(app.Path.Equals(virtualPath))
						{
							exists = true;
							break;
						}
					}

					//不存在才创建
					if(!exists)
					{
						var app = targetSite.Applications.Add(virtualPath, physicalPath);

						//处理poolName
						if(!poolName.IsNullOrEmpty())
							app.ApplicationPoolName = poolName;

						//处理ssl
						if(useSsl)
						{
							var root = server.GetApplicationHostConfiguration();
							var location = root.GetSection("system.webServer/security/access", string.Format("{0}{1}", targetSite.Name, app.Path));
							location["sslFlags"] = 8;
						}

						server.CommitChanges();
					}
					else
					{
						errorCode = ErrorCode.AppExists;
					}
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int RemoveApp(string siteName, string virtualPath)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//先找站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				if(targetSite != null)
				{
					//再找应用
					Application targetApp = null;
					foreach(var app in targetSite.Applications)
					{
						if(app.Path.Equals(virtualPath))
						{
							targetApp = app;
							break;
						}
					}

					//存在才删除
					if(targetApp != null)
					{
						targetSite.Applications.Remove(targetApp);
						server.CommitChanges();
					}
					else
					{
						errorCode = ErrorCode.AppNotFound;
					}
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int SetCertificate(string siteName, string sslHash)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//找指定站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				//存在才后续处理
				if(targetSite != null)
				{
					foreach(var binding in targetSite.Bindings)
					{
						//只处理https协议
						if(binding.Protocol.EqualsEx("https"))
						{
							binding.CertificateHash = HexString2Bytes(sslHash);
							server.CommitChanges();
							break;
						}
					}
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}

		public int SetPort(string siteName, int httpPort, int httpsPort)
		{
			int errorCode = ErrorCode.Succeed;

			try
			{
                ServerManager server = new ServerManager();//创建iis管理对象
				//找指定站点
				Site targetSite = null;
				foreach(var site in server.Sites)
				{
					if(site.Name.EqualsEx(siteName))
					{
						targetSite = site;
						break;
					}
				}

				//存在才后续处理
				if(targetSite != null)
				{
					foreach(var binding in targetSite.Bindings)
					{
						if(httpPort > 0 && binding.Protocol.EqualsEx("http"))
						{
							binding.BindingInformation = string.Format("*:{0}:", httpPort);
						}

						if(httpsPort > 0 && binding.Protocol.EqualsEx("https"))
						{
							binding.BindingInformation = string.Format("*:{0}:", httpsPort);
						}
					}
					server.CommitChanges();
				}
				else
				{
					errorCode = ErrorCode.SiteNotFound;
				}
			}
			catch(Exception ex)
			{
				errorCode = ErrorCode.Unknown;
				Console.WriteLine(ex.Message);
			}

			return errorCode;
		}
        /// <summary>
        /// 获取站点信息
        /// </summary>
        /// <returns></returns>
        public List<string> GetSiteInfo()
        {
            //创建存储对象
            List<string> sitelist = new List<string>();//站点列表
            System.IO.DirectoryInfo directory;//创建路径对象
            int siteID = 0;//站点ID
            string ServerComment = "";//站点描述
            string password = "";//站点密码
            string ServerPath = "";//站点目录
            long maxBands = 0;//最大绑定数
            long maxConnections = 0;//最大连接数
            string logPath = "";//日志文件存储路径
            string createTime = "";//站点创建时间
            string sitestate = "";//站点状态
            string sitestype = "";//站点类型
            string currentServerBindings;//绑定主机头IP端口字符串
            string[] currentBingdings = new string[2];//绑定主机头和端口
            string siteBindings = "";//当前站点绑定字串
            string cpulimit = "";//CPU限制
            string memeory = "";//内存限制
            string netversion = "";//ASP.NET版本
            string phppath = "";//php path
            string homepages = "";//home page
            string poolname = "";//应用程序池名

            try
            {
                //遍历站点
                ServerManager server = new ServerManager();
                foreach (var site in server.Sites)
                {
                    /*
                     * 站点描述
                     */
                    ServerComment = site.Name;
                    try //拿到应用池名
                    {
                        poolname = addsiteUtil.getPoolName(ServerComment);
                    }
                    catch
                    {

                    }
                    if (poolname == "")
                    {
                        poolname = ServerComment;
                    }
                    /*
                     * 站点绑定域名和端口
                     */
                    foreach (Binding binding in site.Bindings)
                    {
                        try
                        {
                            currentServerBindings = binding.GetAttributeValue("BindingInformation").ToString();
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[1], 0);
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[2], 1);
                            if (currentBingdings[1] == "")
                            {
                                siteBindings += "localhost:" + currentBingdings[0] + ",";
                            }
                            else
                            {
                                siteBindings += currentBingdings[1] + ":" + currentBingdings[0] + ",";
                            }
                        }
                        catch
                        {

                        }
                    }
                    try
                    {
                        //格式域名 消除最后的逗号
                        siteBindings = siteBindings.Substring(0, siteBindings.Length - 1);
                    }
                    catch
                    {

                    }
                    /*
                    * 获取站点目录
                    */
                    Configuration config = server.GetApplicationHostConfiguration();
                    ConfigurationSection sitesection = config.GetSection("system.applicationHost/sites");
                    ConfigurationElementCollection sites = sitesection.GetCollection();
                    foreach (ConfigurationElement siteinfo in sites)
                    {
                        string sitename = siteinfo.GetAttributeValue("name").ToString();
                        if (sitename == ServerComment)
                        {
                            /*
                             * 获取CPU和内存限制
                             */
                            try
                            {
                                cpulimit = (server.ApplicationPools[poolname].Cpu.Limit / 1000).ToString();
                                memeory = (server.ApplicationPools[poolname].Recycling.PeriodicRestart.Memory / 1024).ToString();
                            }
                            catch { }
                            /*
                             * 获取ASP.NET版本
                             */
                            try
                            {
                                netversion = server.ApplicationPools[poolname].ManagedRuntimeVersion;
                            }
                            catch { }
                            password = FtpUtil.GetPassword(poolname);
                            siteID = Convert.ToInt32(siteinfo.GetAttributeValue("id").ToString());//获取站点ID
                            /*
                             * 获取站点状态和站点类型
                             */
                            sitestype = siteinfo.ElementTagName;
                          
                            Site statesite = server.Sites[sitename];

                            string ss = "";
                            try
                            {
                                 ss = statesite.State.ToString();

                                NLogger.Error(statesite.Name+":"+ss);
                            }
                            catch (Exception ex)
                            {
                                NLogger.Error(ex.ToString());
                                ss = "";
                            }
                          

        //                    Starting = 0,
        //Started = 1,
        //Stopping = 2,
        //Stopped = 3,
        //Unknown = 4

                         //   sitestate = ss== "Started"? "Started": "Stopped";

                            sitestate = ss !="" ? ss : "未知";

                            try
                            {
                                if (statesite.Bindings.Count == 1)
                                {
                                    foreach (Binding binding in statesite.Bindings)
                                    {
                                        if (binding.GetAttributeValue("BindingInformation").ToString() == "*:21:")
                                        {
                                            sitestype = "ftp";
                                        }
                                        else
                                        {
                                            //sitestate = statesite.State.ToString();
                                        }
                                    }
                                }
                                else
                                {
                                    //sitestate = statesite.State.ToString();
                                }
                            }
                            catch (Exception ex)
                            {
                                NLogger.Error(ex.ToString());

                            }
                            
                            /*
                             * 获取日志路径
                             */
                            logPath = siteinfo.GetChildElement("logFile").GetAttributeValue("directory").ToString() + "\\W3SVC" + siteID;//获取日志路径
                            /*
                             * 获取最大连接数和绑定数
                             */
                            try
                            {
                                maxBands = Convert.ToInt64(siteinfo.GetChildElement("limits").GetAttributeValue("maxBandwidth").ToString()) / 1024 / 1024;
                                maxConnections = Convert.ToInt64(siteinfo.GetChildElement("limits").GetAttributeValue("maxConnections").ToString());
                            }
                            catch (Exception ex)
                            {
                                NLogger.Error(ex.ToString());
                                maxBands = 0;//无限制
                                maxConnections = 0;//无限制
                            }

                            ServerPath = siteinfo.GetCollection()[0].GetCollection()[0].GetAttributeValue("physicalPath").ToString();
                            /*
                            * 获取站点创建时间
                            */
                            if (Directory.Exists(ServerPath))
                            {
                                directory = new System.IO.DirectoryInfo(ServerPath);
                                createTime = directory.CreationTime.ToString("yyyy-MM-dd");
                            }
                            else
                            {
                                createTime = DateTime.Now.ToString("yyyy-MM-dd");
                            }
                        }
                    }
                    /*
                    * 获取PHP路径
                    */
                    phppath = addsiteUtil.GetPhpEngine(ServerComment);
                    /*
                     * 获取首页
                     */
                    homepages = addsiteUtil.GetDefaultDocument(ServerComment);
                    /*
                    * 添加当前站点信息到列表
                    */
                    sitelist.Add(siteID + "-@-" + ServerComment + "-@-" + siteBindings + "-@-" + ServerPath + "-@-" + createTime + "-@-" + logPath + "-@-" + poolname + "-@-" + password + "-@-" + maxBands + "-@-" + maxConnections + "-@-" + cpulimit + "-@-" + memeory + "-@-" + netversion + "-@-" + sitestype + "-@-" + sitestate + "-@-" + phppath + "-@-" + homepages);
                    siteBindings = "";//初始化域名
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                //errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }
            return sitelist;
        }
        /// <summary>
        /// 获取新站点信息
        /// </summary>
        /// <returns></returns>
        public string GetNewSiteInfo(string newsitename)
        {
            //创建存储对象
            string newsite = "";//新站点
            System.IO.DirectoryInfo directory;//创建路径对象
            int siteID = 0;//站点ID
            string ServerComment = "";//站点描述
            string password = "";//站点密码
            string ServerPath = "";//站点目录
            long maxBands = 0;//最大绑定数
            long maxConnections = 0;//最大连接数
            string logPath = "";//日志文件存储路径
            string sitestate = "";//站点状态
            string sitestype = "";//站点类型
            string createTime = "";//站点创建时间
            string currentServerBindings;//绑定主机头IP端口字符串
            string[] currentBingdings = new string[2];//绑定主机头和端口
            string siteBindings = "";//当前站点绑定字串
            string cpulimit = "";//CPU限制
            string memeory = "";//内存限制
            string netversion = "";//ASP.NET版本
            string phppath = "";//php path
            string homepages = "";//home page
            string poolname = "";//应用程序池名

            try
            {
                //遍历站点
                ServerManager server = new ServerManager();
                foreach (var site in server.Sites)
                {
                    if (site.Name == newsitename)
                    {
                        /*
                         * 站点描述
                         */
                        ServerComment = site.Name;
                        try //拿到应用池名
                        {
                            poolname = addsiteUtil.getPoolName(ServerComment);
                        }
                        catch
                        {

                        }
                        if (poolname == "")
                        {
                            poolname = ServerComment;
                        }
                        password = FtpUtil.GetPassword(poolname);
                        /*
                         * 站点绑定域名和端口
                         */
                        foreach (Binding binding in site.Bindings)
                        {
                            currentServerBindings = binding.GetAttributeValue("BindingInformation").ToString();
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[1], 0);
                            currentBingdings.SetValue(currentServerBindings.Split(":".ToArray())[2], 1);
                            if (currentBingdings[1] == "")
                            {
                                siteBindings += "localhost:" + currentBingdings[0] + ",";
                            }
                            else
                            {
                                siteBindings += currentBingdings[1] + ":" + currentBingdings[0] + ",";
                            }
                        }
                        //格式域名 消除最后的逗号
                        siteBindings = siteBindings.Substring(0, siteBindings.Length - 1);
                        /*
                        * 获取站点目录
                        */
                        Configuration config = server.GetApplicationHostConfiguration();
                        ConfigurationSection sitesection = config.GetSection("system.applicationHost/sites");
                        ConfigurationElementCollection sites = sitesection.GetCollection();
                        foreach (ConfigurationElement siteinfo in sites)
                        {
                            string sitename = siteinfo.GetAttributeValue("name").ToString();
                            if (sitename == ServerComment)
                            {
                                /*
                                * 获取CPU和内存限制
                                */
                                cpulimit = (server.ApplicationPools[poolname].Cpu.Limit / 1000).ToString();
                                memeory = (server.ApplicationPools[poolname].Recycling.PeriodicRestart.Memory / 1024).ToString();
                                /*
                                 * 获取站点状态和站点类型
                                 */
                                sitestype = siteinfo.ElementTagName;
                                Site statesite = server.Sites[sitename];
                              //  sitestate = "Started";



                                string ss = "";
                                try
                                {
                                    ss = statesite.State.ToString();

                                    NLogger.Error(statesite.Name + ":" + ss);
                                }
                                catch (Exception ex)
                                {
                                    NLogger.Error(ex.ToString());
                                    ss = "";
                                }


                                //                    Starting = 0,
                                //Started = 1,
                                //Stopping = 2,
                                //Stopped = 3,
                                //Unknown = 4

                                //   sitestate = ss== "Started"? "Started": "Stopped";

                                sitestate = ss != "" ? ss : "未知";





                                try
                                {
                                    if (statesite.Bindings.Count == 1)
                                    {
                                        foreach (Binding binding in statesite.Bindings)
                                        {
                                            if (binding.GetAttributeValue("BindingInformation").ToString() == "*:21:")
                                            {
                                                sitestype = "ftp";
                                            }
                                            else
                                            {
                                                //sitestate = statesite.State.ToString();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //sitestate = statesite.State.ToString();
                                    }
                                }
                                catch
                                {

                                }
                                /*
                                * 获取ASP.NET版本
                                */
                                try
                                {
                                    netversion = server.ApplicationPools[poolname].ManagedRuntimeVersion;
                                }
                                catch { }

                                siteID = Convert.ToInt32(siteinfo.GetAttributeValue("id").ToString());//获取站点ID
                                int count = siteinfo.ChildElements.Count();
                                /*
                                 * 获取日志路径
                                 */
                                logPath = siteinfo.GetChildElement("logFile").GetAttributeValue("directory").ToString() + "\\W3SVC" + siteID;//获取日志路径
                                /*
                                 * 获取最大连接数和绑定数
                                 */
                                try
                                {
                                    maxBands = Convert.ToInt64(siteinfo.GetChildElement("limits").GetAttributeValue("maxBandwidth").ToString()) / 1024 / 1024;
                                    maxConnections = Convert.ToInt64(siteinfo.GetChildElement("limits").GetAttributeValue("maxConnections").ToString());
                                }
                                catch
                                {
                                    maxBands = 0;//无限制
                                    maxConnections = 0;//无限制
                                }

                                ServerPath = siteinfo.GetCollection()[0].GetCollection()[0].GetAttributeValue("physicalPath").ToString();
                                /*
                                * 获取站点创建时间
                                */
                                if (Directory.Exists(ServerPath))
                                {
                                    directory = new System.IO.DirectoryInfo(ServerPath);
                                    createTime = directory.CreationTime.ToString("yyyy-MM-dd");
                                }
                                else
                                {
                                    createTime = DateTime.Now.ToShortDateString().ToString();
                                }
                            }
                        }
                        /*
                         * 获取PHP路径
                         */
                        phppath = addsiteUtil.GetPhpEngine(ServerComment);
                        /*
                         * 获取首页
                         */
                        homepages = addsiteUtil.GetDefaultDocument(ServerComment);
                        /*
                         * 添加当前站点信息到列表
                         */
                        newsite = siteID + "-@-" + ServerComment + "-@-" + siteBindings + "-@-" + ServerPath + "-@-" + createTime + "-@-" + logPath + "-@-" + poolname + "-@-" + password + "-@-" + maxBands + "-@-" + maxConnections + "-@-" + cpulimit + "-@-" + memeory + "-@-" + netversion + "-@-" + sitestype + "-@-" + sitestate + "-@-" + phppath + "-@-" + homepages;
                    }
                }
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                //errorCode = ErrorCode.Unknown;
                Console.WriteLine(ex.Message);
            }
            return newsite;
        }

        /// <summary>
        /// 获取所有ftp站点信息
        /// </summary>
        /// <param name="newsitename"></param>
        /// <returns></returns>
        public List<string> GetFtpInfos()
        {
            return FtpUtil.GetFtpInfos();
        } 
        /// <summary>
        /// 删除ftp站点
        /// </summary>
        /// <param name="ftpname"></param>
        /// <returns></returns>
        public bool DeleteFtp(string ftpname)
        {

            return FtpUtil.DeleteFtp(ftpname);
        }
        /// <summary>
        /// 获取站点路径
        /// </summary>
        /// <param name="sitename"></param>
        /// <returns></returns>
        public string GetSitePath(string sitename)
        {
            string ServerPath = "";//站点目录
            try
            {
                //遍历站点
                ServerManager server = new ServerManager();
                /*
                * 获取站点目录
                */
                Configuration config = server.GetApplicationHostConfiguration();
                ConfigurationSection sitesection = config.GetSection("system.applicationHost/sites");
                ConfigurationElementCollection sites = sitesection.GetCollection();
                foreach (ConfigurationElement siteinfo in sites)
                {
                    string tsitename = siteinfo.GetAttributeValue("name").ToString();
                    if (tsitename == sitename)
                    {
                        ServerPath = siteinfo.GetCollection()[0].GetCollection()[0].GetAttributeValue("physicalPath").ToString();
                    }
                }
            }
            catch
            {
                return "";
            }
            return ServerPath;

        }
        /// <summary>
        /// 获取所有站点名称
        /// </summary>
        /// <returns></returns>
        public List<string> GetSiteNames()
        {
            List<string> sitenames = new List<string>(); ;//站点目录
            try
            {
                //遍历站点
                ServerManager server = new ServerManager();
                foreach (var site in server.Sites)
                {
                    try
                    {
                        string x = site.Name;
                        //string sitestate = site.State.ToString();
                        sitenames.Add(site.Name);
                    }
                    catch
                    {

                    }
                }
            }
            catch
            {
                return null;
            }
            return sitenames;
        }
        /// <summary>
        /// 删除FTP站点
        /// </summary>
        /// <returns></returns>
        public bool DeleteFtp(IUtil util, string ftpname)
        {
            return FtpUtil.DeleteFtp(ftpname);
        }
        /// <summary>
        /// 判断FTP是否存在
        /// </summary>
        /// <param name="ftpname"></param>
        /// <returns></returns>
        public bool ExistsFtp(string ftpname)
        {
            FtpUtil ftputil = new FtpUtil();
            return ftputil.getFtpState(ftpname);
        }
        /// <summary>
        /// 创建FTP
        /// </summary>
        /// <param name="ftpname"></param>
        /// <param name="ftppass"></param>
        /// <returns></returns>
        public int CreateFtp(string ftpname, string ftppass, string path)
        {  
            try
            {
                int errorCode = ErrorCode.Succeed;
                FtpUtil ftputil = new FtpUtil();
                if (ftputil.getFtpState(ftpname))
                {
                    return ErrorCode.ftpExists;
                }
                //创建FTP用户
                if (addsiteUtil.AddUser(ftpname, ftppass, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                {
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }
                 
                  
                //设置FTP站点权限
                addsiteUtil.icaclsSet(ftpname, path);
                  

                //创建FTP
                return ftputil.createFtpPoint(ftpname, path);       
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                throw ex;
                return ErrorCode.ftpSiteFail;
            }
        }


        public int CreateFtp(bool rw, string ftpname, string ftppass, string path)
        {
            try
            {
                int errorCode = ErrorCode.Succeed;
                FtpUtil ftputil = new FtpUtil();
                if (ftputil.getFtpState(ftpname))
                {
                    return ErrorCode.ftpExists;
                }
                //创建FTP用户
                if (addsiteUtil.AddUser(ftpname, ftppass, System.Configuration.ConfigurationManager.AppSettings.Get("cusercomment"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                {
                    errorCode = ErrorCode.UserNotAdd;
                    return errorCode;
                }

                NLogger.Info("创建FTP用户");
              //  Thread.Sleep(3000);
                //设置FTP站点权限
              addsiteUtil.icaclsSet(ftpname, path);
                 
                  
                //创建FTP
                return ftputil.createFtpPoint(ftpname, path);



            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                throw ex;
                return ErrorCode.ftpSiteFail;
            }
            finally
            { 
                //设置FTP站点权限
                //   addsiteUtil.icaclsSet(rw, ftpname, path);
              new   FtpUtil().SetFtpAccessnew(ftpname, rw);
            }
        }




        #region 创建伪静态配置
        public int CreateRewriteRule(string sitename, string sitepath)
        {
            int errorCode = ErrorCode.Succeed;

            return errorCode;
        }
        /// <summary>
        /// SEO友好规则
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="strdomain"></param>
        /// <param name="isadd"></param>
        /// <returns></returns>
        //public static bool setseorule(string sitename, string sitepath)
        //{
        //    try
        //    {
        //        string webconfig_path = sitepath + @"\web.config";
        //        makewebconfig(siteName, "", "configuration/system.webServer/rewrite/rules");

        //        XmlDocument doc = new XmlDocument();
        //        doc.Load(strFileName);
        //        XmlNode xmlNodex = doc.SelectSingleNode("configuration/system.webServer/rewrite/rules");
        //        if (xmlNodex == null) { return false; }
        //        for (int i = xmlNodex.ChildNodes.Count - 1; i >= 0; i--)
        //        {
        //            if (xmlNodex.ChildNodes[i].Name == "rule")
        //            {
        //                if (xmlNodex.ChildNodes[i].Attributes["name"].Value.StartsWith("s5e6o8rules"))
        //                {
        //                    xmlNodex.RemoveChild(xmlNodex.ChildNodes[i]);
        //                }
        //            }
        //        }
        //        if (isadd == true)
        //        {
        //            XmlDocument docx2 = new XmlDocument();
        //            docx2.Load(@"C:\autosystem\config\webconfig\seo");
        //            XmlNode xmlNodex2 = docx2.SelectSingleNode("rules");
        //            if (xmlNodex2 == null) { return false; }
        //            for (int jji = 0; jji < xmlNodex2.ChildNodes.Count; jji++)
        //            {
        //                if (xmlNodex2.ChildNodes[jji].Name == "rule")
        //                {
        //                    if (xmlNodex2.ChildNodes[jji].Attributes["name"].Value == "s5e6o8rules0")
        //                    {
        //                        XmlNode xmlNodex4 = xmlNodex2.ChildNodes[jji].SelectSingleNode("action");
        //                        xmlNodex4.Attributes["url"].Value = "http://" + strdomain.ToLower() + "/{R:1}";
        //                        XmlNode xmlNodex5 = xmlNodex2.ChildNodes[jji].SelectSingleNode("conditions/add");
        //                        xmlNodex5.Attributes["pattern"].Value = "^" + strdomain.Replace(".", @"\.") + "$";
        //                    }
        //                }
        //            }

        //            foreach (XmlNode item in docx2.SelectSingleNode("rules"))
        //            {
        //                xmlNodex.AppendChild(doc.ImportNode(item, true));
        //            }
        //        }
        //        doc.Save(strFileName);
        //    }
        //    catch (Exception exc)
        //    {
        //        EventLog.WriteEntry("autosystem", System.Reflection.MethodBase.GetCurrentMethod().Name.ToString() + ":" + exc.Message, EventLogEntryType.Error);
        //        return false;
        //    }
        //    return true;
        //}
        #endregion

        #region 删除用户-回滚
        public int DeleteSiteUsers()
        {
            /*----- errorCode ----*/
            int errorCode = ErrorCode.CommitOK;
            try
            {
                //遍历站点
                ServerManager server = new ServerManager();
                foreach (var site in server.Sites)
                {
                    /*
                     * 站点描述
                     */
                    string ServerComment = site.Name;
                    try
                    {
                        /*---- 删除站点用户 ----*/
                        if (ADUser.ExistUser(ServerComment))
                        {
                            ADUser.RemoveGroupUser(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"), ServerComment);
                        }
                        /*---- 删除应用池用户 ----*/
                        if (ADUser.ExistUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + ServerComment))
                        {
                            ADUser.RemoveGroupUser(System.Configuration.ConfigurationManager.AppSettings.Get("cpoolgp"), System.Configuration.ConfigurationManager.AppSettings.Get("cpoolname") + ServerComment);
                        }
                    }
                    catch
                    {

                    }
                }
            }
            catch
            {
                errorCode = ErrorCode.CommitFail;
            }
            /*--- return ----*/
            return errorCode;
        }
        #endregion

        #region add 301 httpredirect
        public int HttpRedirectAdd(string source_url, string target_url, string sitename)
        {
            /*--- errorCode ----*/
            int errorCode = ErrorCode.CommitOK;
            try//try
            {
                /*--- get redirect sites ----*/
                ServerManager server = new ServerManager();
                Configuration config = server.GetApplicationHostConfiguration();
                ConfigurationSection sitesection = config.GetSection("system.applicationHost/sites");
                ConfigurationElementCollection sites = sitesection.GetCollection();
                //sitename
                string current_sitename = "";
                bool redirectexists_flag = false;
                foreach (ConfigurationElement siteinfo in sites)
                {
                    //sitename
                    current_sitename = siteinfo.GetAttributeValue("name").ToString();
                    //compare
                    if(current_sitename.StartsWith(System.Configuration.ConfigurationManager.AppSettings.Get("redirectname")))
                    {
                        //path
                        string current_sitepath = siteinfo.GetCollection()[0].GetCollection()[0].GetAttributeValue("physicalPath").ToString();
                        //regular
                        string webconfig_path = current_sitepath + @"\web.config";
                        if (System.IO.File.Exists(webconfig_path))//IO
                        {
                            //exists
                            if (RedirectExists(webconfig_path, target_url))
                            {
                                redirectexists_flag = true;
                                break;
                            }
                        }
                    }
                }
                //exists
                if (redirectexists_flag)
                {
                    try//try
                    {
                        //bind domain
                        Site site = server.Sites.FirstOrDefault(o => o.Name == current_sitename);//查找到指定站点
                        site.Bindings.Add(string.Format("*:{0}:{1}", "80", source_url), "http");
                        server.CommitChanges();
                    }
                    catch
                    {
                        errorCode = ErrorCode.saveNewSiteFail;
                    }
                }
                else//not exists
                {
                    //add new redirect site
                    string redirect301_path = CreateRedirectSite(sitename, source_url, target_url);
                    //regular
                    if (redirect301_path != "")
                    {
                        /*---- add 301 redirect ----*/
                        try
                        {
                            //webconfig
                            string webconfig_path = redirect301_path + @"\web.config";
                            //delete webconfig
                            if (System.IO.File.Exists(webconfig_path))
                            {
                                try
                                {
                                    System.IO.File.Delete(webconfig_path);
                                }
                                catch { }
                            }
                            //move file
                            System.IO.File.Copy(System.Environment.CurrentDirectory + @"\data\web.config", webconfig_path,true);
                            //rule
                            Dictionary<string, string> rule = new Dictionary<string, string>();
                            rule.Add("enabled", "true"); rule.Add("destination", target_url); rule.Add("httpResponseStatus", "Permanent");
                            //xmlhelper
                            XmlHelper xmlHelper = new XmlHelper(webconfig_path);
                            //创建redirect节点
                            xmlHelper.AppendSubNode(@"//configuration/system.webServer", "httpRedirect");
                            xmlHelper.AppendSubNode_Q(@"//configuration/system.webServer/httpRedirect", rule);
                        }
                        catch
                        {
                            errorCode = ErrorCode.SetFail;
                        }
                    }
                    else
                    {
                        errorCode = ErrorCode.siteStateError;
                    }
                }
            }
            catch
            {
                errorCode = ErrorCode.CommitFail;
            }
            return errorCode;
        }
        /// <summary>
        /// jduge redirect rule exists or no
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool RedirectExists(string path,string target_url)
        {
            try//try
            {
                //xmlhelper
                XmlHelper xmlHelper = new XmlHelper(path);
                string xpath_redirect = @"//configuration/system.webServer/httpRedirect";
                //get destination
                string destination = xmlHelper.GetAttributeValue(xpath_redirect, "destination");
                //compare
                if (destination == target_url)
                {
                    return true;
                }
                //no
                return false;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// add redirect site
        /// </summary>
        /// <param name="siteinfo"></param>
        /// <returns></returns>
        public string CreateRedirectSite(string sitename,string source_url,string target_url)
        {
            try//try
            {
                ServerManager server = new ServerManager();//IIS管理对象
                //path
                string redirect301_path = System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath") + @"\" + sitename;
                string redirectpath = System.Configuration.ConfigurationManager.AppSettings.Get("redirectname");
                string redirectname = redirectpath.Substring(0, redirectpath.Length - 1);
                /*
                 * 创建用户
                 */
                if (addsiteUtil.UserExist(System.Configuration.ConfigurationManager.AppSettings.Get("cusergp"), redirectname) != ErrorCode.UserExist)
                {
                    if (addsiteUtil.AddUser_Q(redirectname, System.Configuration.ConfigurationManager.AppSettings.Get("redirectpass"), System.Configuration.ConfigurationManager.AppSettings.Get("redirectcomm"), System.Configuration.ConfigurationManager.AppSettings.Get("cusergp")) == ErrorCode.UserNotAdd)
                    {
                        return "";
                    }
                }
                /*
                 * 创建目录
                 */
                try
                {
                    //create path
                    if (!System.IO.Directory.Exists(redirect301_path))
                    {
                        System.IO.Directory.CreateDirectory(redirect301_path);
                        /*---- hide ----*/
                        addsiteUtil.icaclsSet(redirectname, redirect301_path);//icacls
                        System.IO.File.SetAttributes(System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath"), System.IO.FileAttributes.Hidden);
                        System.IO.File.SetAttributes(redirect301_path, System.IO.FileAttributes.Hidden);
                    }
                }
                catch
                {
                    //create disk c path
                    try
                    {
                        //path
                        redirect301_path = "C:" + System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath").Substring(2) + @"\" + sitename;
                        //create path
                        if (!System.IO.Directory.Exists(redirect301_path))
                        {
                            System.IO.Directory.CreateDirectory(redirect301_path);
                            /*---- hide ----*/
                            addsiteUtil.icaclsSet(redirectname, redirect301_path);//icacls
                            System.IO.File.SetAttributes(System.Configuration.ConfigurationManager.AppSettings.Get("redirectpath"), System.IO.FileAttributes.Hidden);
                            System.IO.File.SetAttributes(redirect301_path, System.IO.FileAttributes.Hidden);
                        }
                    }
                    catch
                    {
                        return "";
                    }
                }
                /*
                 * 创建站点
                 */
                try
                {
                    //启用父目录
                    addsiteUtil.SetAspParent();

                    //初始化站点
                    Site site = server.Sites.Add(sitename, "http", string.Format("*:{0}:{1}", "80", source_url), redirect301_path);
                    /*
                     * no log
                     */
                    SiteLogFile logfile = site.LogFile;
                    logfile.Enabled = false;
                    /*
                     * 设置站点访问权限
                     */
                    Application app = site.Applications[0];
                    VirtualDirectory virdir = app.VirtualDirectories[0]; //site.VirtualDirectoryDefaults;
                    virdir.UserName = redirectname;
                    virdir.Password = System.Configuration.ConfigurationManager.AppSettings.Get("redirectpass");
                    //提交更改
                    server.CommitChanges();
                    /*
                    * 指定应用程序池
                    */
                    //addsiteUtil.connectPool(sitename, "DefaultAppPool");
                }
                catch
                {
                    return "";
                }
                /*
                 * 将新建的站点数据存储到数据库表
                 */
                IISAdoHelper.adoSaveNewSite(sitename);
                //return
                return redirect301_path;
            }
            catch
            {
                return "";
            }
        }
        #endregion
    }
}
